﻿
using Microsoft.AspNetCore.Authentication;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using PCH.Entities;
using PCH.Services.Dto;

namespace PCH.Services
{
    public class AuditService : IAuditService
    {
        private readonly EFDbContext _db;
        private readonly ICommonService _commonService;
        private readonly ILogger _logger;
        private readonly IConfiguration _configuration;

        public AuditService(EFDbContext dbContext,
                            ICommonService commonService,
                            ILogger<AuditService> logger,
                            IConfiguration configuration)
        {
            _db = dbContext;
            _commonService = commonService;
            _logger = logger;
            _configuration = configuration;
        }


        public List<object> GetCardData(DateTime startTime, DateTime endTime)
        {
            _logger.LogInformation("startTime:" + startTime.ToString());
            _logger.LogInformation("startTime:" + startTime.ToString());
            endTime = endTime.Date.AddDays(1);
            List<object> items = new List<object>();
            try
            {
                var registerCount = _db.Registers.Where(r => r.F_STU_BES_DATE > startTime && r.F_STU_BES_DATE < endTime).Count();
                var resultCount = _db.ExamResults.Where(e => e.reportDT > startTime && e.reportDT < endTime).Count();
                _logger.LogInformation("登記量：" + registerCount.ToString());
                _logger.LogInformation("完成兩：" + resultCount.ToString());

                Dictionary<string, object> item1 = new Dictionary<string, object>();
                item1.Add("category", "登记");
                item1.Add("total", registerCount);
                if (startTime == DateTime.Now.Date && endTime == startTime.AddDays(1))
                {
                    item1.Add("label", "今天");
                }
                else
                {
                    item1.Add("label", "");
                }
                items.Add(item1);

                Dictionary<string, object> item2 = new Dictionary<string, object>();
                item2.Add("category", "完成");
                item2.Add("total", resultCount);
                if (startTime == DateTime.Now.Date && endTime == startTime.AddDays(1))
                {
                    item2.Add("label", "今天");
                }
                else
                {
                    item2.Add("label", "");
                }
                items.Add(item2);

            }
            catch (Exception e)
            {
                _logger.LogError(e.Message.ToString());
            }
            return items;
        }


        /// <summary>
        /// 获取表格数据
        /// </summary>
        /// <param name="startTime"></param>
        /// <param name="endTime"></param>
        /// <returns></returns>
        public List<AuditViewModel> GetTableData(DateTime startTime, DateTime endTime, int page, int perPage ,out int count)
        {
            string PACS = _configuration["DataBaseName:PACS"];
            string BESPOKE = _configuration["DataBaseName:BESPOKE"];
            string bespokeSql = @$"SELECT   
                                                                CAST(F_STU_BES_DATE AS DATE) AS AuditDate,
                                                                COUNT(*) AS RegisterCount
                                                                FROM
                                                                    {BESPOKE}.dbo.T_BESPOKE
                                                                Where  F_STU_BES_DATE > '{startTime.ToString()}' and F_STU_BES_DATE< '{endTime.ToString()}'
                                                                GROUP BY 
                                                                    CAST(F_STU_BES_DATE AS DATE)
                                                                ORDER BY AuditDate desc";
            var beSpokeList = _db.BeSpokes.FromSqlRaw(bespokeSql).ToList();
            count = beSpokeList.Count;
            string basicSql = @$"SELECT 
                                                        CAST(F_STU_DATE AS DATE) AS AuditDate,
                                                        COUNT(DISTINCT F_STU_BES_GUID) AS CompletedCount
                                                    FROM 
	                                                    {PACS}.dbo.T_STUDY_BASIC
                                                    Where F_STU_DATE >='{startTime}' And F_STU_DATE<= '{endTime}'
                                                    GROUP BY 
                                                        CAST(F_STU_DATE AS DATE)
                                                    ORDER BY 
                                                        AuditDate desc";
            var bascList = _db.Bascs.FromSqlRaw(basicSql).ToList();
            List<AuditViewModel> list = new List<AuditViewModel>();

            foreach (var item in beSpokeList)
            {
                var basics = bascList.Where(e => e.AuditDate == item.AuditDate).ToList();
                Basc basic = null;
                if (basics.Count > 0)
                {
                    basic = basics[0];
                }
                int completedCount = basic == null ? 0 : basic.CompletedCount;
                var unDoCount = item.RegisterCount - completedCount >= 0 ? item.RegisterCount - completedCount : 0;
                double completedPec = (Convert.ToDouble(completedCount)/Convert.ToDouble(item.RegisterCount)) * 100;
                completedPec = completedPec >= 100 ? 100 : completedPec;
                double unDoRate = (Convert.ToDouble(unDoCount) /Convert.ToDouble(item.RegisterCount)) * 100;
                unDoRate = unDoRate < 0 ? 0 : unDoRate;
                list.Add(new AuditViewModel
                {
                    AuditDate = item.AuditDate.ToString("yyyy-MM-dd"),
                    RegistCount = item.RegisterCount,
                    CompletedCount = completedCount,
                    UnDoCount = unDoCount,
                    CompletedPec =Math.Round(completedPec,1).ToString()+"%",
                    UnDoRate =Math.Round(unDoRate,1).ToString()+"%"
                });
            }
            list = list.Skip((page - 1) * perPage).Take(perPage).ToList();

            return list;
        }
    }
}
